import type { CardItem } from '../types/cardData';
import { getConfig } from './configService';
import { ElMessage } from 'element-plus';

// 创建简单的消息映射
const errorMessages: Record<string, string> = {
  'errors.networkError': '网络错误，请检查网络连接',
  'errors.apiError': 'API请求失败: {0}',
  'errors.cardNotFound': '未找到卡片数据',
  'errors.serverError': '服务器错误: {0}',
  'errors.unknownError': '未知错误'
};

// 简单的翻译函数
function translate(key: string, params?: any[]): string {
  let message = errorMessages[key] || key;
  if (params) {
    params.forEach((param, index) => {
      message = message.replace(`{${index}}`, param);
    });
  }
  return message;
}

// 获取API基础URL
async function getApiBaseUrl(): Promise<string> {
  const config = await getConfig();
  return config.dataSource.apiBaseUrl || 'http://localhost:8080/api';
}

// 检查是否使用Mock数据
async function shouldUseMockData(): Promise<boolean> {
  const config = await getConfig();
  return config.dataSource.useMockData || false;
}

// 处理API请求错误
function handleApiError(error: any, customMessage?: string): string {
  console.error('API请求错误:', error);
  
  let errorMessage: string;
  
  if (error instanceof TypeError && error.message.includes('fetch')) {
    errorMessage = translate('errors.networkError');
  } else if (error.status) {
    errorMessage = translate('errors.serverError', [error.status]);
  } else {
    errorMessage = customMessage || translate('errors.apiError', [error.message || '未知错误']);
  }
  
  // 显示错误提示
  ElMessage.error(errorMessage);
  
  return errorMessage;
}

// 获取卡片列表
export async function fetchRemoteCards(page: number, pageSize: number): Promise<{
  items: CardItem[];
  hasMore: boolean;
  total: number;
}> {
  if (await shouldUseMockData()) {
    // 如果配置为使用Mock数据，则委托给mockService处理
    const { fetchMockCards } = await import('./mockService');
    return fetchMockCards(page, pageSize);
  }

  // 否则请求实际的远程API
  const baseUrl = await getApiBaseUrl();
  const url = `${baseUrl}/cards?page=${page}&size=${pageSize}`;
  
  try {
    const response = await fetch(url);
    if (!response.ok) {
      const errorMsg = `请求失败: ${response.status} ${response.statusText}`;
      handleApiError({ status: response.status, message: response.statusText }, 
                     `获取卡片列表失败 (${response.status})`);
      throw new Error(errorMsg);
    }
    
    return await response.json();
  } catch (error) {
    handleApiError(error, '获取卡片列表失败');
    // 返回空结果
    return {
      items: [],
      hasMore: false,
      total: 0
    };
  }
}

// 获取单个卡片
export async function getRemoteCard(cardId: string): Promise<CardItem | null> {
  if (await shouldUseMockData()) {
    // 如果配置为使用Mock数据，则委托给mockService处理
    const { getMockCard } = await import('./mockService');
    return getMockCard(cardId);
  }

  // 否则请求实际的远程API
  const baseUrl = await getApiBaseUrl();
  const url = `${baseUrl}/cards/${cardId}`;
  
  try {
    const response = await fetch(url);
    if (!response.ok) {
      if (response.status === 404) {
        handleApiError({ status: 404, message: '卡片不存在' }, '未找到卡片数据');
        return null;
      }
      const errorMsg = `获取卡片详情失败: ${response.status} ${response.statusText}`;
      handleApiError({ status: response.status, message: response.statusText }, 
                     `获取卡片详情失败 (${response.status})`);
      throw new Error(errorMsg);
    }
    
    return await response.json();
  } catch (error) {
    handleApiError(error, `获取卡片 ${cardId} 失败`);
    return null;
  }
}

// 保存卡片
export async function saveRemoteCard(card: Partial<CardItem>): Promise<CardItem> {
  if (await shouldUseMockData()) {
    // 如果配置为使用Mock数据，则委托给mockService处理
    const { saveMockCard } = await import('./mockService');
    return saveMockCard(card);
  }

  // 否则请求实际的远程API
  const baseUrl = await getApiBaseUrl();
  const url = card.id 
    ? `${baseUrl}/cards/${card.id}` // 更新现有卡片
    : `${baseUrl}/cards`;           // 创建新卡片
  
  try {
    const response = await fetch(url, {
      method: card.id ? 'PUT' : 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(card)
    });
    
    if (!response.ok) {
      const action = card.id ? '更新' : '创建';
      const errorMsg = `${action}卡片失败: ${response.status} ${response.statusText}`;
      handleApiError({ status: response.status, message: response.statusText }, 
                      `${action}卡片失败 (${response.status})`);
      throw new Error(errorMsg);
    }
    
    return await response.json();
  } catch (error) {
    const action = card.id ? '更新' : '创建';
    handleApiError(error, `${action}卡片失败`);
    // 在保存失败的情况下，我们需要抛出异常，让调用者知道操作失败了
    throw error;
  }
}

// 删除卡片
export async function deleteRemoteCard(cardId: string): Promise<boolean> {
  if (await shouldUseMockData()) {
    // 如果配置为使用Mock数据，则委托给mockService处理
    const { deleteMockCard } = await import('./mockService');
    return deleteMockCard(cardId);
  }

  // 否则请求实际的远程API
  const baseUrl = await getApiBaseUrl();
  const url = `${baseUrl}/cards/${cardId}`;
  
  try {
    const response = await fetch(url, {
      method: 'DELETE'
    });
    
    if (!response.ok) {
      const errorMsg = `删除卡片失败: ${response.status} ${response.statusText}`;
      handleApiError({ status: response.status, message: response.statusText }, 
                     `删除卡片失败 (${response.status})`);
      throw new Error(errorMsg);
    }
    
    return response.ok;
  } catch (error) {
    handleApiError(error, `删除卡片 ${cardId} 失败`);
    return false;
  }
}

// 批量删除卡片
export async function batchDeleteRemoteCards(cardIds: string[]): Promise<{ success: boolean; count: number }> {
  if (await shouldUseMockData()) {
    // 如果配置为使用Mock数据，则委托给mockService处理
    const { batchDeleteMockCards } = await import('./mockService');
    return batchDeleteMockCards(cardIds);
  }

  // 否则请求实际的远程API
  const baseUrl = await getApiBaseUrl();
  const url = `${baseUrl}/cards/batch`;
  
  try {
    const response = await fetch(url, {
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ ids: cardIds })
    });
    
    if (!response.ok) {
      const errorMsg = `批量删除卡片失败: ${response.status} ${response.statusText}`;
      handleApiError({ status: response.status, message: response.statusText }, 
                     `批量删除卡片失败 (${response.status})`);
      throw new Error(errorMsg);
    }
    
    return await response.json();
  } catch (error) {
    handleApiError(error, '批量删除卡片失败');
    return {
      success: false,
      count: 0
    };
  }
} 